package cate.game.server.schedule;

import cate.game.ManyGame;
import cate.game.server.schedule.task.EstimateHealthTask;
import cate.game.server.schedule.task.ProcessTaskExecutable;
import cate.game.server.schedule.task.SaveDbTask;
import cp.game.framework.ManyGameConfig;
import cp.solution.business.game.cmd.ProcessTaskEntity;
import cp.solution.manage.PrimaryClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class ProcessTaskHandler implements InitializingBean {

    private Timer timer = new Timer();

    private ManyGameConfig config;
    private ManyGame games;
    private PrimaryClient pc;

    public ProcessTaskHandler(ManyGameConfig config, ManyGame games) {
        this.config = config;
        this.pc = games.api.pc();
        this.games = games;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    exe();
                } catch (Exception e) {
                    log.error("定时任务异常", e);
                } catch (Error e) {
                    log.error("定时任务错误", e);
                } catch (Throwable t) {
                    log.error("定时任务未知错误", t);
                }
            }
        }, 60_000, 60_000);
    }

    private void exe() throws Exception {
        log.debug("进程任务exe");
        ProcessTaskEntity task = pc.console.processTask.retrieveOne(this.config.processCode);
        if(task != null) {
            log.info("执行进程任务task={}", task);
            task.setAcceptTime(new Date());
            pc.console.processTask.update(task);
            ProcessTaskExecutable handler = null;
            try {
                switch (task.getCmd()) {
                    case ProcessTaskEntity.CMD_ESTIMATE_HEALTH:
                        handler = new EstimateHealthTask();
                        break;
                    case ProcessTaskEntity.CMD_SAVE_DB:
                        handler = new SaveDbTask();
                        break;
                }
                if(handler != null) {
                    handler.init(task, games, pc);
                    task.setResult(handler.exe());
                } else {
                    task.setResult("没有实现对应的功能");
                }
            } catch (Exception ex) {
                log.error("", ex);
                task.setResult(ex.getMessage());
            }
            task.setFinishTime(new Date());
            pc.console.processTask.update(task);
        }
    }




}
